package com.amos.teaching_aids.ui.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class ViewHolderHelper {
    private View mConvertView;//item layout
    private SparseArray<View> mViews;//集合类，layout里包含的View,以view的id作为key，value是view对象
    private Context mContext;//上下文对象
    private int position;//子项item的位置

    /**
     * 私有的构造方法，外界通过静态方法get()获取对象
     * 初始化成员变量
     */
    private ViewHolderHelper(Context context, ViewGroup parent, int layoutId, int position) {
        this.mContext = context;
        this.position = position;
        this.mViews = new SparseArray<View>();
        //动态加载子项布局
        this.mConvertView = LayoutInflater.from(mContext).inflate(layoutId, parent, false);
        mConvertView.setTag(this);
    }

    public View getView() {
        return mConvertView;
    }

    public static ViewHolderHelper get(Context context, View convertView, ViewGroup parent, int layoutId, int position) {
        /**
         * 若convertView==null，证明该item的layout view未被缓存过，则调用VIewHolderHelper的构造函数动态加载
         * item布局并打标签；若convertView不为空，直接返回convertView内的Tag*/
        if (convertView == null) {
            return new ViewHolderHelper(context, parent, layoutId, position);
        }
        ViewHolderHelper existingHelper = (ViewHolderHelper) convertView.getTag();
        existingHelper.position = position;
        return existingHelper;
    }

    private <T extends View> T findViewById(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public ViewHolderHelper setText(int viewId, String value) {
        TextView view = findViewById(viewId);
        view.setText(value);
        return this;
    }


    public ViewHolderHelper setBackground(int viewId, int resId) {
        View view = findViewById(viewId);
        view.setBackgroundResource(resId);
        return this;
    }



    public ViewHolderHelper setClickListener(int viewId, View.OnClickListener listener) {
        View view = findViewById(viewId);
        view.setOnClickListener(listener);
        return this;
    }

    public int getPosition() {
        return position;
    }
}